﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Windows.Forms;

namespace SiteMapMerging
{
    public class TextBoxDragDrop
    {
        private bool _isFile;
        private List<string> _extensions;

        public TextBoxDragDrop(TextBox textBox, bool isFile = false, List<string> extensions = null)
        {
            _isFile = isFile;
            _extensions = extensions;

            textBox.AllowDrop = true;
            textBox.DragEnter += TextBox_DragEnter;
            textBox.DragDrop += TextBox_DragDrop;
        }

        private void TextBox_DragDrop(object sender, DragEventArgs e)
        {
            string path = ((System.Array)e.Data.GetData(DataFormats.FileDrop)).GetValue(0).ToString();
            TextBox textBox = sender as TextBox;
            textBox.Text = path;
            textBox.Cursor = Cursors.IBeam;
        }

        private void TextBox_DragEnter(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent(DataFormats.FileDrop))
            {
                string path = ((Array)e.Data.GetData(DataFormats.FileDrop)).GetValue(0).ToString();
                if ((File.GetAttributes(path) & FileAttributes.Directory) == FileAttributes.Directory)
                {
                    //拖进来的是文件夹
                    if (_isFile) { e.Effect = DragDropEffects.None; return; }

                }

                if ((File.GetAttributes(path) & FileAttributes.Archive) == FileAttributes.Archive)
                {
                    //拖进来的是文件
                    if (!_isFile) { e.Effect = DragDropEffects.None; return; }
                    string extension = Path.GetExtension(path).ToLower().Trim();
                    if (_extensions != null && !_extensions.Contains(extension))
                    { e.Effect = DragDropEffects.None; return; }
                }

                e.Effect = DragDropEffects.Link;
                TextBox textBox = sender as TextBox;
                textBox.Cursor = Cursors.Arrow;
            }
            else
            {
                e.Effect = DragDropEffects.None;
            }
        }
    }
}
